/**
 * Created with hong.rong
 * Description:使用图片校验码
 * Date:2020/06/29
 */

import { useState, useEffect, useCallback } from 'react'
import { getVerifyCode } from '@/services/login'

export default function useCodeVerify() {
  const [loading, setLoading] = useState(false)
  const [imgUrl, setImgUrl] = useState('')

  useEffect(() => {
    async function getCode() {
      await handleFetchCode()
    }
    getCode()
  }, [])
  /**
   * 获取code
   * @param url
   * @param data
   * @returns {Promise<*>}
   */
  const handleFetchCode = useCallback(async () => {
    setLoading(true)
    try {
      const { data = {} } = await getVerifyCode()
      if (data) {
        const base64 = new Buffer(data, 'binary').toString('base64')
        setImgUrl(`data:image/png;base64,${base64}`)
        setLoading(false)
      } else {
        setLoading(false)
      }
    } catch (e) {
      console.log(e)
      setLoading(false)
    }
  }, [])

  return {
    loading,
    url: imgUrl,
    refresh: handleFetchCode,
  }
}
